#include "FileManager.h"
#include "iostream"
using namespace std;

Record** FileManager::trainingData;
Record** FileManager::testingData;

FileManager::FileManager(void)
{
}

FileManager::~FileManager(void)
{
}

void FileManager::Init()
{
	//init training data memory
	FileManager::trainingData = (Record**)malloc(sizeof(Record*) * Util::n_trainingRecord);
	for(int i = 0; i < Util::n_trainingRecord; ++i)
	{
		FileManager::trainingData[i] = (Record*)malloc(sizeof(Record));
		FileManager::trainingData[i]->recordID = new string();
		FileManager::trainingData[i]->classLab = new string();
		FileManager::trainingData[i]->attributes = (double*)malloc(sizeof(double) * Util::n_dimension);
	}

	//init testing data memory
	FileManager::testingData = (Record**)malloc(sizeof(Record*) * Util::n_testingRecord);
	for(int i = 0; i < Util::n_testingRecord; ++i)
	{
		FileManager::testingData[i] = (Record*)malloc(sizeof(Record));
		FileManager::testingData[i]->recordID = new string();
		FileManager::testingData[i]->classLab = new string();
		FileManager::testingData[i]->attributes = (double*)malloc(sizeof(double) * Util::n_dimension);
	}
}

void FileManager::Load_Data()
{
	FILE* trainingFile = fopen(Util::trainingFilePath.c_str(),"r");
	for(int i = 0; i < Util::n_trainingRecord; ++i)
	{
		char * temp = (char *)malloc(sizeof(char) * 1024);
		fscanf(trainingFile, "%s", temp);
		*(FileManager::trainingData[i]->recordID) = temp;
		fscanf(trainingFile, "%s", temp);
		*(FileManager::trainingData[i]->classLab) = temp;
		for(int j = 0; j < Util::n_dimension; ++j)
		{
			fscanf(trainingFile, "%s", temp);
			FileManager::trainingData[i]->attributes[j] = Util::char_p_To_double(temp);
		}
	}
	fclose(trainingFile);

	FILE* testingFile = fopen(Util::testingFilePath.c_str(),"r");
	for(int i = 0; i < Util::n_testingRecord; ++i)
	{
		char * temp = (char *)malloc(sizeof(char) * 1024);
		fscanf(testingFile, "%s", temp);
		*(FileManager::testingData[i]->recordID) = temp;
		fscanf(testingFile, "%s", temp);
		*(FileManager::testingData[i]->classLab) = temp;
		for(int j = 0; j < Util::n_dimension; ++j)
		{
			fscanf(testingFile, "%s", temp);
			FileManager::testingData[i]->attributes[j] = Util::char_p_To_double(temp);
		}
	}
	fclose(testingFile);
}

void FileManager::Self_Test()
{
	//cout << "hello";
	//cout << Util::n_trainingRecord << endl;
	for(int i = 0; i < Util::n_trainingRecord; ++i)
	{
		cout << FileManager::trainingData[i]->recordID << endl;
		cout << FileManager::trainingData[i]->classLab << endl;
		for(int j = 0; j < Util::n_dimension; ++j)
		{
			cout << FileManager::trainingData[i]->attributes[j] << endl;
		}
	}
}
